<template>
  <div class="m-pageView">
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item class="input-with-select">
                <el-input placeholder=" " v-model.trim="searchForm.inputFH" clearable>
                  <el-select v-model="searchForm.typeinputFH" slot="prepend" placeholder="请选择"
                             class="selectInputType">
                    <el-option label="用户" value="nickname"></el-option>
                    <el-option label="姓名" value="realName"></el-option>
                    <el-option label="电邮" value="email"></el-option>
                    <el-option label="呼叫系统座席号" value="serviceNumber"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7" class="searchBtns" :offset="11">
              <el-button type="text"
                         @click="showMoreSearchChoise =!showMoreSearchChoise"><span>更多条件</span>
                <i :class="{
                    'el-icon-arrow-down':!showMoreSearchChoise,
                    'el-icon-arrow-up':showMoreSearchChoise,
                    }"></i>
              </el-button>
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询
              </el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
          <el-collapse-transition>
            <el-row :gutter="30" v-if="showMoreSearchChoise">
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-select v-model="searchForm.accountStatus" placeholder="请选择">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="角色">
                  <el-select v-model="searchForm.roleId" placeholder="请选择">
                    <el-option v-for="role in availableRoles" :key="role.id" :label="role.name"
                               :value="role.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-transition>
        </el-form>
      </div>
    </div>
      <div class="m-dataLayout">
        <div class="m-searchListPanel">
          <div class="layout-1"><span class="leftLine"></span>信息列表</div>
          <div class="layout-2">
            <el-button type="text" icon="el-icon-plus" @click="addRowDataDialog"
                       v-if="buttonAuthority.user && buttonAuthority.user.create">新建
            </el-button>
          </div>
        </div>
        <div class="m-dataList">
          <el-table
            :data="dataList"
            style="width: 100%"
            v-loading="dataListLoading"
            element-loading-text="loading..."
            ref="dataList"
            max-height="500"
          >
            <el-table-column
              prop="accountStatus"
              label="状态"
              width="70">
              <template slot-scope="scope">
                <i :class="scope.row.accountStatus==2 ? 'el-icon-circle-close' : 'el-icon-circle-check'"></i>
                <span>
                    {{scope.row.accountStatus == 2 ? "禁用" : "启用"}}
                  </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="nickname"
              label="用户"
              width="100">
            </el-table-column>
            <el-table-column
              prop="realName"
              label="姓名"
              width="200">
            </el-table-column>
            <el-table-column
              prop="email"
              min-width="260"
              label="电邮">
            </el-table-column>
            <el-table-column
              prop="roles"
              label="角色"
              :formatter="formatterRoles"
              width="120">
            </el-table-column>
            <el-table-column
              prop="serviceNumber"
              label="呼叫系统座席号"
              width="150">
            </el-table-column>
            <el-table-column
              prop="createUser"
              label="创建人"
              width="120">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="160">
            </el-table-column>
            <el-table-column
              prop="updateUser"
              label="更新人"
              width="120">
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              width="160">
            </el-table-column>
            <el-table-column
              prop="operations"
              fixed="right"
              align="center"
              v-if="buttonAuthority.user && (buttonAuthority.user.edit||buttonAuthority.user.delete||buttonAuthority.user.reset_pwd)"
              label="更多操作"
              width="110">
              <template slot-scope="scope">
                <el-dropdown trigger="click"
                             @command="type => handleOperation(type, scope.row)">
                  <el-button
                    type="text"
                    icon="el-icon-arrow-down"
                    size="small">
                    更多操作
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="editUser" v-if="buttonAuthority.user && buttonAuthority.user.edit">编辑
                    </el-dropdown-item>
                    <el-dropdown-item command="resetPassword"
                                      v-if="buttonAuthority.user && buttonAuthority.user.reset_pwd">重置密码
                    </el-dropdown-item>
                    <el-dropdown-item command="deleteUser" v-if="buttonAuthority.user && buttonAuthority.user.delete">删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="m-pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=pagination.pageNo
            :page-sizes=pagination.pageSizeList
            :page-size=pagination.pageSize
            layout="total, sizes, prev, pager, next"
            :total=pagination.total>
          </el-pagination>
        </div>
      </div>
      <el-dialog
        :title="dialogEditMode ? '编辑用户' : '创建用户'"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="closeAddDialog"
        class="m-dialog"
        width="600px">
        <el-form :model="userForm" ref="userForm" :rules="rules" :inline="true" label-position="left"
                 label-width="110px">
          <el-form-item label="用户" prop="nickname">
            <el-input v-model="userForm.nickname" placeholder="由字母、数字、下划线" :disabled="dialogEditMode"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="realName">
            <el-input placeholder="" v-model="userForm.realName"></el-input>
          </el-form-item>
          <el-form-item label="电邮地址" prop="email">
            <el-input placeholder="" v-model="userForm.email" :disabled="dialogEditMode"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-select v-model="userForm.roles" placeholder="请选择">
              <el-option v-for="role in availableRoles" :key="role.id" :label="role.name"
                         :value="role.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="呼叫系统座席号">
            <el-input v-model="userForm.serviceNumber"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="userForm.accountStatus" placeholder="请选择">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible =false">取 消</el-button>
          <el-button type="primary" @click="submitUserForm" :loading="addLoading">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="重置密码"
        :visible.sync="resetPasswordVisible"
        :close-on-click-modal="false" :close-on-press-escape="false"
        class="m-dialog"
        width="450px">
        <el-form :model="activeRow" :inline="true" label-position="left" label-width="80px">
          <el-form-item label="用户">
            <el-input v-model="activeRow.nickname" disabled></el-input>
          </el-form-item>
          <el-form-item label="电邮地址">
            <el-input v-model="activeRow.email" disabled></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetPasswordVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResetPassword">确定</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<script>
  import {mapGetters} from "vuex";
  import * as Utils from "@/utils";
  import * as userAPI from "@/Api/user";
  import * as roleAPI from "@/Api/role";
  export default {
    name: "User",
    data() {
      return {
        showMoreSearchChoise: false,  //显示更多筛选条件
        activeRow: {}, //当前操作的数据
        resetPasswordVisible: false,//重置密码弹窗显示隐藏
        dialogVisible: false,
        dialogEditMode: false,
        availableRoles: [],//角色列表
        dataList: [],
        dataListLoading: false,
        addLoading: false,
        copySearchForm: null,
        searchForm: {
          typeinputFH: 'nickname',
          inputFH: '',
          roleId: '',
          accountStatus: "",
        },
        userForm: {},
        rules: {
          nickname: [
            {required: true, message: "请输入用户名称", trigger: "blur"},
            {min: 3, message: "长度在 3 个字符以上", trigger: "blur"},
            {pattern: /^[a-zA-Z0-9\_]+$/, trigger: "blur", message: "用户名格式错误",}
          ],
          realName: [
            {required: true, message: "请输入用户昵称", trigger: "blur"},
            {min: 3, message: "长度在 3 个字符以上", trigger: "blur"}
          ],
          email: [
            {required: true, message: "请输入用户邮箱地址", trigger: "blur"},
            {min: 3, message: "长度在 3 个字符以上", trigger: "blur"}
          ],
          roles: {required: true, message: "请选择用户角色", trigger: "blur"}
        },
        pagination: Utils.commonPagination(),
        ajaxSearchParams:{},
      };
    },
    computed: {
      ...mapGetters(["buttonAuthority"]),
      accountNo() {
        return this.$store.state.app.userInfo.accountNo
      }
    },
    created(){
      this.copySearchForm = Object.assign({}, this.searchForm);
      this.getAvailableRoles()
        .then(() => {
          this.search();
        })
    },
    methods: {
      getAvailableRoles() {
        return new Promise((reslove, reject) => {
          roleAPI.roleQuery()
            .then(res => {
              if (res.code != '0') {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warn'
                })
                reject();
                return;
              }
              this.availableRoles = res.data;
              reslove();
            })
            .catch(error => {
              console.log(error);
              reject();
            })
        })
      },
      formatterRoles(row, cellValue) {
        for (let i = 0; i < this.availableRoles.length; i++) {
          if (this.availableRoles[i].id == row.roles) {
            return this.availableRoles[i].name
          }

        }
      },
      closeAddDialog() {
        this.$refs.userForm.resetFields();
      },
      addRowDataDialog(){
        this.userForm = {
          accountNo: "",
          nickname: "",
          realName: "",
          email: "",
          roles: "",
          serviceNumber: "",
          accountStatus: 1
        };
        this.dialogEditMode = false;
        this.dialogVisible = true;
      },
      createListParams() {
        return Object.assign(this.ajaxSearchParams, {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        })
      },
      queryData() {
        this.dataListLoading = true;
        if (this.$refs.dataList) {
          this.$refs.dataList.bodyWrapper.scrollTop = 0;
        }
        userAPI.userQuery(this.createListParams())
          .then(res => {
            this.dataListLoading = false;
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.dataList = res.data.list;
            this.pagination.total = res.data.total;
          })
          .catch(error => {
            this.dataListLoading = false;
            console.log(error)
          })
      },
      handleOperation(type, row) {
        this.activeRow = Object.assign({}, row);
        switch (type) {
          case "editUser":
            this.userForm = Object.assign({}, this.activeRow);
            this.dialogVisible = true;
            this.dialogEditMode = true;
            break;
          case "resetPassword":
            this.resetPasswordVisible = true;
            break;
          case "deleteUser":
            this.onUserDelete();
        }
      },
      reset() {
        this.searchForm = Object.assign({}, this.copySearchForm);
      },
      search() {
        this.ajaxSearchParams = Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryData();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryData();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryData();
      },
      onUserDelete() {
        this.$confirm(`确认删除用户${this.activeRow.nickname}?`, "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(_ => {
            userAPI.userDelete({
              accountNo: this.activeRow.accountNo,
              nickname: this.activeRow.nickname
            })
              .then(res => {
                if (res.code != 0) {
                  this.$notify.warning({
                    title: '温馨提示',
                    message: res.msg
                  })
                  return;
                }
                this.$message.success("用户删除成功！");
                this.queryData();
              })
          })
          .catch(_ => {
          });
      },
      submitUserForm() {
        this.$refs.userForm.validate(flg => {
          if (!flg) {
            return;
          }
          this.addLoading = true;
          let params = {};
          if (this.dialogEditMode) {
            //编辑
            params = Object.assign({}, this.userForm, Utils.updateFormItemCopy(this.activeRow));
          } else {
            //新建
            params = this.userForm;
          }
          userAPI[this.dialogEditMode ? 'userEdit' : 'userCreate'](params)
            .then(res => {
              this.addLoading = false;
              if (res.code != '0') {
                this.$notify.warning({
                  title: '温馨提示',
                  message: res.msg
                })
                return;
              }
              if (this.dialogEditMode && this.userForm.accountNo == this.accountNo) {
                window.location.reload()
              }
              this.search();
              this.dialogVisible = false;
              this.$message.success(`${this.dialogEditMode ? '修改' : '新建'}成功`)
            })
            .catch(error => {
              this.addLoading = false;
              console.log(error);
            })
        })
      },
      submitResetPassword() {
        userAPI.userResetPwd({
          email: this.activeRow.email
        })
          .then(res => {
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.resetPasswordVisible = false;
            this.$message.success("密码重置成功!");
          })
          .catch(error => {
            console.log(error)
          })
      }
    }
  };
</script>

<style scoped lang="scss"></style>
